<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--card卡片-->
    <el-card class="box-card">
      <!--警告-->
      <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false"></el-alert>
      <!--级联选择框-->
      <div class="selectCate">
        <span>选择商品分类：</span>
        <el-cascader
          v-model="selectValue"
          :options="cateOptions"
          :props="cateProp"
          @change="selectChange">
        </el-cascader>
      </div>
      <!--tabs标签页-->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many" :disabled="disabled">
          <el-button type="primary" :disabled="disabled" @click="addDialogVisible=true">添加参数</el-button>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only" :disabled="disabled">
          <el-button type="primary" :disabled="disabled" @click="addDialogVisible=true">添加属性</el-button>
        </el-tab-pane>
      </el-tabs>
      <!--表格-->
      <el-table
        border stripe
        :data="tableDataList"
        style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-tag
              @close="handleClose(index, scope.row)"
              closable
              v-for="(item, index) in scope.row.attr_vals"
              :key="index">
              {{item}}
            </el-tag>
            <el-input class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput" size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)">
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialogShow(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delParamAttr(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!---->
    <!---->
    <!---->
    <!--添加动态参数、添加静态属性-->
    <el-dialog
      :title="activeName==='many'?'添加动态参数':'添加静态属性'"
      :visible.sync="addDialogVisible"
      width="50%" @close="addDialogClose">
      <el-form :model="addParamAttr" :rules="addParamAttrRules" ref="addParamsRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="addParamAttr.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamAttrForm">确 定</el-button>
      </span>
    </el-dialog>
    <!---->
    <!---->
    <!---->
    <!--修改动态参数-->
    <el-dialog
      :title="activeName==='many'?'修改动态参数':'修改静态属性'"
      :visible.sync="editDialogVisible"
      width="50%">
      <el-form :model="editParamAttr" :rules="editParamAttrRules" ref="editParamsRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="editParamAttr.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamAttrForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        // 级联选择框
        selectValue: [],
        cateOptions: [],
        cateProp: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // tabs标签页
        activeName: 'many',
        // 表格
        tableDataList: [],
        // 添加动态参数、静态属性Dialog对话框
        addDialogVisible: false,
        addParamAttr: {
          attr_name: ''
        },
        addParamAttrRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' }
          ]
        },
        // 编辑动态参数、静态属性Dialog对话框
        editInfo: {},
        editDialogVisible: false,
        editParamAttr: {
          attr_name: ''
        },
        editParamAttrRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' }
          ]
        }
      }
    },
    created () {
      this.getCategories()
    },
    computed: {
      disabled: function() {
        if (this.selectValue.length !== 3) {
          return true
        }
        return false
      },
      cateId: function() {
        if (this.selectValue.length !== 3) {
          return null
        }
        return this.selectValue[2]
      }
    },
    methods: {
      // 为级联选择框获取商品分类数据列表
      getCategories: async function () {
        const { data: res } = await this.$http.get('categories')
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
        this.cateOptions = res.data
      },
      // 级联选择框选择的值，获取动态参数，获取静态属性
      selectChange: async function () {
        if (this.selectValue.length !== 3) {
          this.selectValue = []
          this.tableDataList = []
          return
        }
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取数据失败！')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        this.tableDataList = res.data
      },
      // tabs标签页
      handleClick(tab) {
        this.activeName = tab.name
        this.selectChange()
      },
      // 添加动态参数、静态属性Dialog对话框关闭事件，清空内容
      addDialogClose: function () {
        this.$refs.addParamsRef.resetFields()
      },
      // 提交添加动态参数、静态属性值
      addParamAttrForm: function () {
        this.$refs.addParamsRef.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addParamAttr.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 201) return this.$message.error('参数值添加失败！')
          this.addDialogVisible = false
          this.$message.success('参数值添加成功！')
          this.selectChange()
        })
      },
      // table表格,关闭Tag标签
      handleClose(index, row) {
        row.attr_vals.splice(index, 1)
        this.saveAttrValue(row)
      },
      // table表格的new Tag展示
      showInput(row) {
        row.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      // table表格的new Tag标签失去焦点、或者按enter键都会触发
      handleInputConfirm: function (row) {
        const inputValue = row.inputValue
        if (inputValue && inputValue.trim().length !== 0) {
          row.attr_vals.push(inputValue)
        }
        this.saveAttrValue(row)
        row.inputVisible = false
        row.inputValue = ''
      },
      // 后台保存编辑提交的参数
      saveAttrValue: async function (row) {
        const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        })
        if (res.meta.status !== 200) {
          row.attr_vals.pop()
          this.$message.error('参数更新失败！')
        } else {
          this.$message.success('参数更新成功！')
        }
      },
      // 编辑动态参数、静态属性Dialog对话框展示
      editDialogShow: function(row) {
        this.editDialogVisible = true
        this.editParamAttr.attr_name = row.attr_name
        this.editInfo = row
      },
      // 提交编辑动态参数、静态属性
      editParamAttrForm: function () {
        this.$refs.editParamsRef.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.put(`categories/${this.editInfo.cat_id}/attributes/${this.editInfo.attr_id}`, {
            attr_name: this.editParamAttr.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 200) return this.$message.error('参数更新失败！')
          this.$message.success('参数更新成功！')
          this.editDialogVisible = false
          this.selectChange()
        })
      },
      // 删除动态参数、静态属性
      delParamAttr: function(row) {
        console.log(row)
        this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败！')
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.selectChange()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .selectCate{
    margin-top: 15px;
  }
  .el-menu{
    margin-bottom: 15px;
  }
  .el-tag{
    margin: 10px;
  }
  .input-new-tag {
    width: 90px;
  }
</style>
